package duyd.transaction.training.service.programmatic;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import duyd.transaction.training.domain.Contact;
import duyd.transaction.training.service.ContactService;

@Service("contactService")
@Repository
public class ContactServiceImpl implements ContactService {

    @Autowired
    private TransactionTemplate transactionTemplate;

    @PersistenceContext
    private EntityManager em;

    public long countAll() {
        return transactionTemplate.execute(new TransactionCallback<Long>() {

            public Long doInTransaction(TransactionStatus status) {
                return em.createNamedQuery("contact.countAll", Long.class).getSingleResult();
            }
        });
    }

    @SuppressWarnings("unchecked")
    public List<Contact> findAll() {
        return em.createNamedQuery("contact.findAll").getResultList();
    }

    public Contact findOne(Long id) {
        return em.find(Contact.class, 1L);
    }

    public Contact save(Contact contact) {
        em.persist(contact);
        return contact;
    }

    public List<Contact> findByFirstNameAndLastName(String firstName, String lastName) {
        return em.createNamedQuery("contact.findByName", Contact.class).setParameter(0, "Scott").setParameter(1, "Tiger").getResultList();
    }

    public List<Contact> findByBirthDate(Date birthDate) {
        try {
            return em.createNamedQuery("contact.findByBirthDate", Contact.class).setParameter(0, new SimpleDateFormat("yyyy-MM-dd").parse("1980-07-30")).getResultList();
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

}
